import axios from 'axios'
import qs from 'qs';
axios.defaults.timeout = 10000
const baseUrl = "http://localhost"

// 一些错误状态码的处理
const errHandle = (status) => {
    switch (status) {
        // 请求不存在
        case 404:
            tip('请求的资源不存在');
            break;
        // 其他原因    
        default:
            console.log("other reasons")
    }
}

// 请求拦截器
axios.interceptors.request.use(
    // 查看本地是否有token,有token就带过去
    config => {
        // console.log(config)
        if (localStorage.getItem('token_key')) {
            config.headers['x-user-token'] = localStorage.getItem('token_key')
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// 响应拦截器
axios.interceptors.response.use(
    // res=>console.log(res),
    res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res),
    err => {
        errHandle(err)
        return Promise.reject(err.status)
    }
)

// 封装get
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios({
            method: "GET",
            url: baseUrl + url,
            params: JSON.stringify(params)
        }).then(
            res => {
                resolve(res)
            }
        ).catch(
            err => {
                reject(err)
            }
        ) 
    })
}

// 封装post
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios({
            method: "POST",
            url: baseUrl + url,
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(params)
        }).then(
            res => {
                resolve(res)
            }
        ).catch(
            err => {
                reject(err)
            }
        )
    })

}
